const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const static = require('koa-static')
const koaBody = require('koa-body');
const fs = require("fs");


//-----------------------------------------------------------------------
const koajwt = require('koa-jwt')
const jwt = require("jsonwebtoken")
const cors = require('koa2-cors');
const path = require('path')


app.use(static(path.join(__dirname, '/public')))

//跨域问题解决
app.use(cors())

//连接数据库
require('./utils/mongoDB')
const fs_main = require('./config/fs')

//用户引入-----------------------------------------------
const users = require('./routes/users')
const cardNumbers = require('./routes/cardNumbers')
//引入大客户
const keyaccounts = require('./routes/keyaccounts') //大客户 22
//引入合伙人
const partners = require("./routes/partners")
//引入订单表
const orders = require("./routes/orders")
const goods = require('./routes/goods') // 商品（卡） 22
//引入活动
const accountSetups = require("./routes/accountSetups")
const industrys = require('./routes/industrys')// 行业 22
//引入用户分组
const groups = require("./routes/groups")
//引入提现表
const withdrawals = require("./routes/withdrawals")

//引入禁止所有接口API模块
const forbiden = require("./config/forbiden")

const router = require('./routes/users')


// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
//引入token处理校验模块
// app.use(forbiden)


// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});


// //token判断
// app.use(koajwt({ secret: "my_token", passthrough: pass }).unless({
//   path: ['/api/login', '/api/register', '/'],
// })
// );


// routes加载---------------------------------------------------
app.use(users.routes(), users.allowedMethods())//管理员
app.use(cardNumbers.routes(), cardNumbers.allowedMethods())//卡号
app.use(keyaccounts.routes(),keyaccounts.allowedMethods())//大客户 22
app.use(partners.routes(), partners.allowedMethods())//合伙人
app.use(orders.routes(), orders.allowedMethods())//订单
app.use(goods.routes(),goods.allowedMethods())//商品（卡） 22
app.use(accountSetups.routes(), accountSetups.allowedMethods())//活动
app.use(industrys.routes(),industrys.allowedMethods())//行业 22
app.use(groups.routes(), groups.allowedMethods())//角色
app.use(withdrawals.routes(), withdrawals.allowedMethods())//提现申请

app.use(koaBody({ multipart: true }));
app.use(fs_main);

module.exports = app
